import mountElement from './mountElement'
import updateTextNode from './updateTextNode'
import updateNodeElement from './updateNodeElement'
import createDomElement from './createDomElement'
import unmountNode from './unmountNode'

export default function diff(virtualDOM, container, oldDom) {

  const oldVirtual = oldDom && oldDom._virtualDOM

  if (!oldDom) {

    mountElement(virtualDOM, container)

  } else if (typeof oldVirtual.type !== 'function' && oldVirtual.type !== virtualDOM.type) {
    const newElement = createDomElement(virtualDOM)
    oldDom.parentNode.replaceChild(newElement, oldDom)

  } else if (oldVirtual && oldVirtual.type === virtualDOM.type) {

    if (virtualDOM.type === 'text') {
      updateTextNode(virtualDOM, oldVirtual, oldDom)
    } else {
      updateNodeElement(oldDom, virtualDOM, oldVirtual)
    }

    virtualDOM.children.forEach((child, i) => {
      diff(child, oldDom, oldDom.childNodes[i])
    })

    if (oldDom.childNodes.length > virtualDOM.children.length) {

      for (
        let i = oldDom.childNodes.length - 1;
        i > virtualDOM.children.length - 1;
        i--) {
        unmountNode(oldDom.childNodes[i])
      }

    }

  }
}